<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <button onclick="init()">初始化</button>
  <button onclick="sendPort1Message()">port1</button>
  <button onclick="sendPort2Message()">port2</button>
  <body>
    <script>
      let port1 = null
      let port2 = null
      function init() {
        console.log('初始化')

        const port = new MessageChannel()
        port1 = port.port1
        port2 = port.port2
        port1.addEventListener('message', e => {
          console.log('port1', e)
        })
        port1.start()
        port2.addEventListener('message', e => {
          console.log('port2', e)
        })
        port2.start()
      }
      function sendPort1Message() {
        if (port1) {
          port1.postMessage('来自port1的消息')
        }
        setTimeout(() => {
          console.log('异步')
        }, 1000)
        Promise.resolve('promise').then(res => {
          console.log(res)
        })
        console.log('同步')
      }
      function sendPort2Message() {
        if (port2) {
          port2.postMessage('来自port2的消息')
        }
      }
    </script>
  </body>
</html>
